from flask_script.commands import Server
import sys
from flask import Flask
from copy import deepcopy
from application import socket_io
from flask.ctx import AppContext


class RunServer(Server):

    def __call__(self, app, host, port, use_debugger, use_reloader,
                 threaded, processes, passthrough_errors, ssl_crt, ssl_key):
        if not isinstance(app, Flask):
            raise Exception('app is not instance flask.Flask')

        if use_debugger is None:
            use_debugger = app.debug
            if use_debugger is None:
                use_debugger = True
                if sys.stderr.isatty():
                    print("Debugging is on. DANGER: Do not allow random users to connect to this server.",
                          file=sys.stderr)
        if use_reloader is None:
            use_reloader = use_debugger

        if None in [ssl_crt, ssl_key]:
            ssl_context = None
        else:
            ssl_context = (ssl_crt, ssl_key)
        option = deepcopy(self.server_options)
        for i in option:
            i = i.upper()
        app.config.update({
            "DEBUG": use_debugger,
            "USE_DEBUGGR": use_debugger,
            "THREDED": threaded,
            "PROCESSES": processes,
            "SSL_CONTEXT": ssl_context,

        })

        app.config.update(option)
        print(host,port)
        with AppContext(app=app):
            socket_io.run(app,host=host,port=port)